

local AOI_ACTION_TYPE = AOI_ACTION_TYPE
local LIBDEMO = _G.libdemo
local printx = debug.printx

function __init__(self)
    self.clsCoreScene:RegTmpVar("SceneUid")   -- 场景编号，也是场景的全局唯一的表示id
	self.clsCoreScene:RegTmpVar("SceneId")    -- 场景资源ID
    self.clsCoreScene:RegTmpVar("AoiRange")   -- 场景user AOI
    self.clsCoreScene:RegTmpVar("AoiMgr")   -- 场景user AOI
end

clsCoreScene = ALL_CLASS.clsCoreObj:Inherit("clsCoreScene")

function clsCoreScene:OnCreate(oci)
    Super(clsCoreScene).OnCreate(self, oci)

	-- 记录当前场景中的所有场景对象
	self.m_ObjSet = {}

    self.m_AllObjByUid = {}
end

function clsCoreScene:ToString()
	return string.format("SceneUid=%s, SceneId=%s", self:GetSceneUid() or 0, self:GetSceneId() or 0)
end

function clsCoreScene:OnDestroy()
	-- 销毁场景内所有已创建的对象
    for _,obj in pairs(self.m_AllObjByUid) do
        if obj.LeaveScene then
            xpcall(function ()
                obj:LeaveScene()
            end)
        end
    end
    self.m_AllObjByUid = {}
	self.m_ObjSet = {}

    self:SetAoiMgr(nil)
	Super(clsCoreScene).OnDestroy(self)
end

function clsCoreScene:OnObjGoto(pos, obj)
    local x,y = table.unpack(pos)
    local ret = self:GetAoiMgr():move(obj:GetUid(), x, y)
    assert(ret, "obj场景移动失败")

    xpcall(obj.OnGoto, debug.excepthook, obj, pos)
end

-- 当有obj进入此场景时会回调该函数
function clsCoreScene:OnObjEnter(pos, obj)
    local aoiMask = obj:GetAoiMask()
    local x,y = table.unpack(pos)
    local ret = self:GetAoiMgr():enter(obj:GetUid(), self:GetAoiRange(), aoiMask.SelfMask, aoiMask.IMask, x, y)
    assert(ret, "obj进入场景失败")

	xpcall(obj.OnEnterScene, debug.excepthook, obj, pos, self)

	-- 将当前obj加入到当前场景的管理器中
	local objType = obj:GetType()
	local uid = obj:GetUid()
	local objList = self.m_ObjSet[objType]
	if not objList then
		self.m_ObjSet[objType] = {[uid] = obj}
	else
		objList[uid] = obj
	end
    self.m_AllObjByUid[uid] = obj
end


-- 当有obj离开此场景时会回调该函数
function clsCoreScene:OnObjLeave(obj)
	-- 将obj从当前场景管理器中移除
	local objList = self.m_ObjSet[obj:GetType()]
	local uid = obj:GetUid()
	objList[uid] = nil
    self.m_AllObjByUid[uid] = nil
    local ret = self:GetAoiMgr():leave(obj:GetUid())
    assert(ret, "obj离开场景失败")
	xpcall(obj.OnLeaveScene, debug.excepthook, obj, self)
end

function clsCoreScene:GetAllObjByType(objType)
	return self.m_ObjSet[objType] or {}
end

function clsCoreScene:GetObj(objType, uid)
	local objList = self.m_ObjSet[objType]
	return objList and objList[uid]
end

function clsCoreScene:GetObjByUid(uid)
	return self.m_AllObjByUid[uid]
end